import React, { Component } from 'react';
import Axios from '../../service/axios';
import Citys from '../../config/citys';
import _ from 'lodash';
import { Icon } from 'antd';
import './style.scss';
import { useState } from 'react';

interface IProps {
    [propName: string]: any,
}
export default class CityList extends Component<IProps, any> {
    constructor(props: IProps) {
        super(props)
        props.cacheLifecycles.didRecover(this.componentDidRecover.bind(this))
    }
    readonly state = {
        cityList: [],
    }
    readonly colorEmue = {
        '晴': '80,178,251',
        '阴': '136,169,202',
        '多云': '80,178,251',
        '小雨': '136,169,202',
    }
    componentDidMount() {
        Axios.get({
            url: 'https://restapi.amap.com/v3/ip?output=json&key=c79aeb4171f72f162217f854cb1f296e',
        }).then(response => {
            let city = response.data.city;
            let cityList = _.filter(Citys, item => {
                return city.indexOf(item.ReadmeName) > -1;
            })
            let localCtys: any = localStorage.getItem('CITY_LIST');
            if (localCtys) {
                localCtys = JSON.parse(localCtys);
                cityList = _.concat(cityList, localCtys)
            }
            this.setState({
                cityList
            })
            _.each(cityList, (item: any) => {
                Axios.get({
                    url: 'http://api.help.bj.cn/apis/weather/',
                    parameter: {
                        id: item.CityCode
                    }
                }).then(data => {
                    if (data.status === 200) {
                        _.merge(item, data.data);
                        this.setState({
                            cityList
                        })
                    }
                })
            })
            console.log(cityList)
        })
    }
    componentDidRecover() {
        Axios.get({
            url: 'https://restapi.amap.com/v3/ip?output=json&key=c79aeb4171f72f162217f854cb1f296e',
        }).then(response => {
            let city = response.data.city;
            let cityList = _.filter(Citys, item => {
                return city.indexOf(item.ReadmeName) > -1;
            })
            let localCtys: any = localStorage.getItem('CITY_LIST');
            if (localCtys) {
                localCtys = JSON.parse(localCtys);
                cityList = _.concat(cityList, localCtys)
            }
            this.setState({
                cityList
            })
            _.each(cityList, (item: any) => {
                Axios.get({
                    url: 'http://api.help.bj.cn/apis/weather/',
                    parameter: {
                        id: item.CityCode
                    }
                }).then(data => {
                    if (data.status === 200) {
                        _.merge(item, data.data);
                        this.setState({
                            cityList
                        })
                    }
                })
            })
            console.log(cityList)
        })
    }
    private onDelete(data: any) {
        const citys = JSON.parse(localStorage.getItem('CITY_LIST') || '');
        localStorage.setItem('CITY_LIST', JSON.stringify(_.filter(citys, (item: any) => {
            return item.id !== data.id;
        })))
        this.setState({
            cityList: _.pull(this.state.cityList, data)
        })
    }
    render() {
        return (
            <div className="CityList" style={{ backgroundImage: "url(../images/bg.jpg)" }}>
                {
                    this.state.cityList.map((item: any, index: number) => (
                        <CityItem
                            key={item.id}
                            ReadmeName={item.ReadmeName}
                            uptime={item.uptime || '--:--'}
                            temp={item.temp || '--'}
                            weatherimg={item.weatherimg || ''}
                            color={this.colorEmue[item.weather] || '80,178,251'}
                            onDelete={this.onDelete.bind(this, item)}
                            onClick={() => { this.props.history.push('/home/' + item.CityCode) }}
                            location={index === 0} />
                    ))
                }
                <div className="btnBox flex">
                    <p>°C/°F</p>
                    <Icon type="plus" onClick={() => { this.props.history.push('/addCity') }} />
                </div>
            </div>
        )
    }
}
interface IProps {
    ReadmeName: string,
    location?: boolean,
    uptime: string,
    temp: string,
    weatherimg: string,
    color: string,
    onClick: () => void,
    onDelete: () => void,
}
const CityItem: React.FC<IProps> = (props) => {
    const { ReadmeName = '', location = false, onClick, onDelete, uptime, temp, weatherimg, color } = props;
    const [isDelete, setIsDelete] = useState(false);
    let startX: number = 0;
    let start: boolean = false
    const onTouchStart = (event: any) => {
        startX = event.touches[0].clientX;
        start = true;
    }
    const onTouchMove = (event: any): any => {
        if (!start || location) return false;
        let endY = event.touches[0].clientX;
        if (endY < startX - 30) {
            setIsDelete(true)
        } else if (endY > startX + 30) {
            setIsDelete(false)
        }
    }
    const onTouchEnd = (event: any) => {
        start = false;
    }
    const OnItemClick = () => {
        if (isDelete) {
            setIsDelete(false)
        } else {
            onClick();
        }
    }
    return (
        <div className={`flex cityItem align-center`}
            style={{ backgroundImage: `url(${weatherimg})`, backgroundColor: `rgba(${color},.5)` }}
            onClick={OnItemClick}
            onTouchStart={onTouchStart}
            onTouchEnd={onTouchEnd}
            onTouchMove={onTouchMove}>
            <div className={`flex wrap ${isDelete ? 'delete' : ''}`}>
                <div className="container flex align-center">
                    <div>
                        <p className="time"><span>{uptime}</span>{location && <Icon type="environment" />}</p>
                        <p>{ReadmeName}</p>
                    </div>
                    <p className="tem">{temp}°C</p>
                </div>
                <button className="deleteBtn" onClick={(e) => { e.stopPropagation(); onDelete() }}>删除</button>
            </div>
        </div>
    )
}
